﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Telerik.Web.UI;
using System.Collections;

public partial class Admin_Components_Member_UserRole : System.Web.UI.UserControl
{
    private long ID = 0 ;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
           
            DBDataContext dtx = LINQUtil.GetDBReadOnly();
            var q = dtx.Combo_Role("");
            cboRole.DataSource = q;
            cboRole.DataTextField = "Name";
            cboRole.DataValueField = "Code";
            cboRole.DataBind();
            cboRole.Items.Insert(0, new RadComboBoxItem("--Chọn--", ""));
            cboRole.SelectedIndex = 0;

            Utils.LoadDataToCombo(cboUser, "Combo_User", DbType.Int32, 0);
            cboUser.Items.Insert(0, new RadComboBoxItem("--Chọn--", ""));
            cboUser.SelectedIndex = 0;

            if (Session["UserRoleID"] != null && !String.IsNullOrEmpty(Session["UserRoleID"].ToString()))
            {
                ID = Convert.ToInt64(Session["UserRoleID"]);
                ViewState["UserRoleID"] = ID;
                var ur = (from a in dtx.UserRoles
                          where a.ID == ID
                          select a).FirstOrDefault();
                if (ur != null)
                {
                    cboRole.SelectedValue = ur.RoleID.ToString();
                    cboUser.SelectedValue = ur.UserID.ToString();
                    loadData();
                }
            }
            Session["UserRoleID"] = null;
            Session.Remove("UserRoleID");
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        DBDataContext dtx = LINQUtil.GetDBWriteOnly();
        UserRole userRole = new UserRole();
        string roleID = this.cboRole.SelectedValue;
        string userID = this.cboUser.SelectedValue;

        if (roleID == "")
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn nhóm quyền");
            cboRole.Focus();
            return;
        }

        if (userID == "")
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn user");
            cboUser.Focus();
            return;
        }

        int userRoleID = ViewState["UserRoleID"] == null ? 0 : Convert.ToInt32(ViewState["UserRoleID"]);
        var UR = (from ur in dtx.UserRoles
                        where ur.UserID == Convert.ToInt16(userID)
                        && ur.ID != userRoleID
                        select ur).FirstOrDefault();
        if (UR != null)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "User "+cboUser.SelectedItem.Text +" đã được phân quyền.");
            return;
        }
        
        if (userRoleID == 0)
        {
            userRole.RoleID = Convert.ToInt16(roleID);
            userRole.UserID = Convert.ToInt16(userID);
            userRole.UserName = "";
            dtx.Insert<UserRole>(userRole);
            JavascriptUtil.LoadMessage(UpdatePanel1, true, "Thành công !");
            dtx.SubmitChanges();
        }
        else if (userRoleID != 0)
        {
            userRole =(from ur in dtx.UserRoles
                        where ur.ID == userRoleID
                        select ur).FirstOrDefault();

            userRole.RoleID = Convert.ToInt32(roleID);
            userRole.UserID = Convert.ToInt32(userID);
            userRole.UserName = "";

            dtx.Update<UserRole>(userRole);
            JavascriptUtil.LoadMessage(UpdatePanel1, true, "Cập nhật thành công !");
            dtx.SubmitChanges();
            
           // cboUser.SelectedIndex = 0;
            //cboRole.SelectedIndex = 0;
        }
        loadData();
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        loadData();
    }

    private void loadData()
    {
        DBDataContext dtx = LINQUtil.GetDBWriteOnly();
        int roleID = this.cboRole.SelectedValue == "" ? 0 : Convert.ToInt32(this.cboRole.SelectedValue);
        int userID = this.cboUser.SelectedValue =="" ?0 : Convert.ToInt32 ( this.cboUser.SelectedValue);

        var list = (from ur in dtx.UserRoles
                    join u in dtx.Users on ur.UserID equals u.ID
                    join r in dtx.Roles on ur.RoleID equals r.ID
                    where (ur.RoleID == roleID || roleID == 0)
                    && (ur.UserID == userID || userID == 0)
                    select new
                    {
                        ur.ID,
                        u.UserName,
                        r.RoleName
                    }).ToList();

        this.grvData.DataSource = list;
        this.grvData.DataBind();
    }
    protected void grvData_ItemCommand(object sender, GridCommandEventArgs e)
    {
        //try
        //{
        string commandName = e.CommandName;

        if (commandName == "EditItem")
        {
           // int iRow = e.Item.ItemIndex;
           // string ID = grvData.Items[iRow]["ID"].Text.Replace("&nbsp;", "");
            string ID = e.CommandArgument.ToString();
            Session["UserRoleID"] = ID;
            Response.Redirect("~/UserRole");
        }

        else if (commandName == "EditDelItem")
        {
            DBDataContext dtx = LINQUtil.GetDBWriteOnly();
          //  /int iRow = e.Item.ItemIndex;
           // string ID = grvData.Items[iRow]["ID"].Text.Replace("&nbsp;", "");
            string ID = e.CommandArgument.ToString();
            var ur = (from a in dtx.UserRoles
                      where a.ID == Convert.ToInt32(ID)
                      select a).FirstOrDefault();
            dtx.Delete<UserRole>(ur);
            dtx.SubmitChanges();
            JavascriptUtil.LoadMessage(UpdatePanel1, true, "Xóa thành công! ");
            Response.Redirect("~/UserRole");
        }
        
    }
}